#!/usr/bin/python -Wignore::DeprecationWarning
#
# flickrbg
#
# Set Flickr images as wallpaper for GNOME desktop
#

import os, sys,re, optparse
import random
import flickrapi, json
import urllib
import gconf

default_api_key = 'XXXX'

def get_photos(api_key, tags):
    flickr = flickrapi.FlickrAPI(api_key, format='json')
    raw = flickr.photos_search(safe_search=1, tag_mode='all', tags=tags)
    rsp = json.loads(re.compile('^jsonFlickrApi\((.*)\)$').sub(r'\1', raw))

    if (rsp['stat'] != "ok"):
        raise Exception(rsp['code'], rsp['message'])

    return rsp['photos']['photo']

def make_url(photo, size=''):
    id     = str(photo['id'])
    farm   = str(photo['farm'])
    server = str(photo['server'])
    secret = str(photo['secret'])
    if (size != ''): size = "_" + size
    return "http://farm" + farm + ".static.flickr.com/" + server + "/" + id + "_" + secret + size + ".jpg"

def set_background(url):
    filename = os.path.join(os.path.expanduser('~'), 'Pictures', 'flickr_bg.jpg')
    urllib.urlretrieve(url, filename)
    if os.path.isfile(filename):
        gconf.client_get_default().set_string('/desktop/gnome/background/picture_filename', filename)

def main():
    usage = "Usage: %prog [options] tag1[,tag2[,...]]"
    parser = optparse.OptionParser(usage = usage)
    parser.add_option("-k", "--key", dest="api_key", default=default_api_key,
                        help="Flickr API key")
    (options, args) = parser.parse_args()

    if (len(args) < 1):
        parser.error("tag is required.")
    tags = args[0]

    try:
        photos = get_photos(options.api_key, tags)
    except Exception as (code,detail):
        print 'FlickrAPI error: [',code,']',detail
    else:
        n = random.randint(0, len(photos))
        set_background(make_url(photos[n]))

if __name__ == '__main__':
    main()

# vim: ts=4 sw=4 et ai enc=utf-8
